from flask import Flask, render_template, request
from werkzeug.routing import BaseConverter


# 正则表达式
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *item):
        super(RegexConverter, self).__init__(url_map)
        self.regex = item[0]


app = Flask(__name__)
app.url_map.converters['regex'] = RegexConverter


@app.route('/')
def hello_world():
    return render_template('index.html', title='Welcome to flask_sample!')


@app.route('/services')
def services():
    return 'Service'


@app.route('/about')
def about():
    return 'About'


# int float path
@app.route('/user/<int:user_id>')
def userid(user_id):
    return 'User %d' % user_id


@app.route('/user/<regex("[a-z]{3}"):user_id>')
def user(user_id):
    return 'User %s' % user_id


# 后面带“/” 匹配规则 从上到下
@app.route('/projects/')
@app.route('/our-works/')
def projects():
    return 'The project page'


@app.route('/login', methods=['GET', 'POST'])
def login():
    return render_template('login.html', method=request.method)


# 加上它 就不报404了
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')


if __name__ == '__main__':
    # 简单研究了一下后，发现是flask 更新到1.0以后 不支持使用debug =True 来开启调试模式了。
    # Pycharm 2018环境中可以直接右键运行按钮左边下拉菜单的Edit Configurations，勾上Flask_Debug后面的小勾就好了。
    # linux环境的话直接
    # export Flask_Debug = 1
    app.run(debug=True)
